
#include<iostream>
#include<cstring>
#include<cstdio>
#include<unistd.h>
#include<sys/epoll.h>


#include"Httpparse.h"

Httpparse::Httpparse(int epfd,struct epoll_event ev){
    fd = ev.data.fd;
    status = -1;
    url = NULL;
    body_buffer = NULL;
    header_buffer = NULL;

    char buf[MAX_READ_BUFFER]="";
    int ret = read(fd,buf,MAX_READ_BUFFER);
    if(ret <= 0){
        return;
    }
    
    char met[16]="";
    char tmp[256]="";
    char ver[16]="";
    
    sscanf(buf,"%16[^ ] %256[^ ] %16[^\r\n]\r\n",met,tmp,ver);
    info("%s %s %s",met,tmp,ver);

    url = (char*)malloc(strlen(tmp)+1);
    if(url == NULL){
        return;
    }
    memcpy(url,tmp,strlen(tmp));
    url[strlen(tmp)]='\0';

    if(strcasecmp(met,"GET")==0)method = M_GET;
    else if(strcasecmp(met,"POST")==0)method = M_POST;
    else if(strcasecmp(met,"HEAD")==0)method = M_HEAD;
    else if(strcasecmp(met,"PUT")==0)method = M_PUT;
    else if(strcasecmp(met,"DELETE")==0)method = M_DELETE;
    else if(strcasecmp(met,"CONNECT")==0)method = M_CONNECT;
    else if(strcasecmp(met,"OPTIONS")==0)method = M_OPTIONS;
    else if(strcasecmp(met,"TRACE")==0)method = M_TRACE;
    else if(strcasecmp(met,"PATCH")==0)method = M_PATCH;
    else return;


    if(strcasecmp(ver,"HTTP/1.0")==0)version = HTTP1_0;
    else if(strcasecmp(ver,"HTTP/1.1")==0)version = HTTP1_1;
    else return ;


    

    int len = strlen(met)+strlen(tmp)+strlen(ver) + 4;
    int buf_len = strlen(buf);

    header_num = 0;
    // char *rec_header[128];

    while(1){
        int w = sscanf(buf+len,"%[^\r\n]\r\n",tmp);
        if(w > 0){
            len +=strlen(tmp) + 2;
            if(len>buf_len)return;

            //解析头部消息
            
            // rec_header[header_num] = (char*)malloc(strlen(tmp));
            // if(rec_header[header_num] == NULL){
            //     return;
            // }
            // memcpy(rec_header[header_num],tmp,strlen(tmp));
            // header_num++;
        }else if(w == 0){
            len+=2;
            break;
        }
    }
    
    // header_buffer = (char **)malloc(sizeof(char*)*header_num);
    // if(header_buffer == NULL){
    //     return;
    // }

    // for(int i=0;i<header_num;i++){
    //     header_buffer[i] = rec_header[i];
    // }

    if(buf_len != len){
        body_buffer = (char*)malloc(buf_len - len +1);
        if(body_buffer == NULL) return;
        memcpy(body_buffer,buf+len,buf_len-len);
        body_buffer[buf_len-len]='\0';
    }
    
    // debug("====::%s %s",url,body_buffer);
    status = 0;
}



Httpparse::~Httpparse(){
    if(body_buffer != NULL) free(body_buffer);
    if(url != NULL) free(url);

    // for(int i=0;i<header_num;i++){
    //     if(header_buffer[i] != NULL) free(header_buffer[i]);
    // }
    // if(header_buffer != NULL) free(header_buffer);
}